package com.example.maoyanmovie.ui.adapter;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.maoyanmovie.databinding.ItemCinemaBinding;
import com.example.maoyanmovie.model.Cinema;
import com.example.maoyanmovie.ui.activity.CinemaDetailActivity;
import com.example.maoyanmovie.utils.Constants;
import java.util.ArrayList;
import java.util.List;

public class CinemaAdapter extends RecyclerView.Adapter<CinemaAdapter.ViewHolder> {

    private Context context;
    private List<Cinema> cinemaList = new ArrayList<>();

    public CinemaAdapter(Context context) {
        this.context = context;
    }

    public void setCinemaList(List<Cinema> cinemaList) {
        this.cinemaList = cinemaList;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        ItemCinemaBinding binding = ItemCinemaBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false);
        return new ViewHolder(binding);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Cinema cinema = cinemaList.get(position);
        holder.bind(cinema);
    }

    @Override
    public int getItemCount() {
        return cinemaList.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder {
        ItemCinemaBinding binding;

        ViewHolder(ItemCinemaBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
        }

        void bind(Cinema cinema) {
            binding.tvName.setText(cinema.getName());
            binding.tvAddress.setText(cinema.getAddress() != null ? cinema.getAddress() : "地址未知");
            binding.tvDistance.setText(cinema.getDistance() != null ? cinema.getDistance() : "距离未知");
            binding.tvCount.setText(cinema.getCount() + "场次");

            binding.getRoot().setOnClickListener(v -> {
                Intent intent = new Intent(context, CinemaDetailActivity.class);
                intent.putExtra(Constants.INTENT_KEY_CINEMA_ID, cinema.getId());
                context.startActivity(intent);
            });
        }
    }
}
